构造器 注入

一、注入引用类型

构造器 注入

Service 层

通过构造器注入,添加构造器,并传入 BookDao

1
2
3
4
5
6
7
8
9
10
11
12
public class BookServiceImpl implements BookService, InitializingBean, DisposableBean {
private BookDao bookDao;

public BookServiceImpl(BookDao bookDao) {
this.bookDao = bookDao;
}

public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}

配置

  • 在 bookService 的 bean 中添加 contructor-arg 标签
  • name 代表要注入的属性:构造器中形参的名称
  • value 代表要注入的值:注入的引用 bean Id
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bookDao" class="cn.pangcy.dao.impl.BookDaoImpl" />
<bean id="bookService" class="cn.pangcy.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao" />
</bean>
</beans>

二、注入简单类型

构造器 注入

Dao 层

创建构造器,并传入属性:type, price

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class BookDaoImpl implements BookDao {
private String type;
private int price;

public BookDaoImpl(String type, int price) {
this.type = type;
this.price = price;
}

@Override
public void save() {
System.out.println("book dao save !!! " + type +": " + price);
}
}

配置

  • 在 bookDao 的 bean 中添加 contructor-arg 标签
  • name 代表要注入的属性:构造器中形参的名称
  • value 代表要注入的值:常量值
1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="bookDao" class="cn.pangcy.dao.impl.BookDaoImpl">
<constructor-arg name="price" value="1020" />
<constructor-arg name="type" value="系统集成" />
</bean>
<bean id="bookService" class="cn.pangcy.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao" />
</bean>
</beans>

构造器 注入
https://blog.pangcy.cn/2023/04/04/后端编程相关/java/spring/构造器 注入/
作者
ziYang | 子洋
发布于
2023年4月4日
许可协议